package com.zhi.controller;

import com.zhi.entity.*;
import com.zhi.service.*;
import com.zhi.util.PageUtil;
import com.zhi.util.UpdateObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 请假学生逻辑Controller层
 */
@Controller
public class LeaveStudentController {

    Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
    TeacherService teacherService;

    @Autowired
    GradeService gradeService;

    @Autowired
    GradeTeacherService gradeTeacherService;

    @Autowired
    LeaveService leaveService;

    @Autowired
    LeaveInfoService leaveInfoService;

    @Autowired
    DictionaryService dictionaryService;

    @Autowired
    MailService mailService;

    //邮件模板
    @Value("${email.template01}")
    String emailTemplate01;

    /**
     * 列表数据-在途请假流程
     * @param model
     * @param pageUtil
     * @return
     */
    @RequestMapping("/toLeaveStudentApply")
    public String toLeaveStudentApply(Model model, PageUtil pageUtil, HttpSession httpSession) {

        //1、从Session中获取登录学生信息
        //Student sessionStudent = new Student("10012016001001",null,null,null,null);
//        Student sessionStudent = (Student)httpSession.getAttribute("sessionStudent");
//        String studentId = sessionStudent.getStudentId();
//
//    	//2、初始化分页工具
//    	pageUtil = PageUtil.init(pageUtil);
//    	Pageable pageable = PageRequest.of(pageUtil.getPageIndex()-1, pageUtil.getSize());
//
//    	//3、查询分页数据
//        List<String> studentIdList = new ArrayList<>();
//        studentIdList.add(studentId);
//        List<String> stateList = new ArrayList<>();
//        stateList.add("0");//申请中
//    	Page<ALeave> pageList= leaveService.getEntityListWithCodeName(pageable,studentIdList,stateList);
//    	List<ALeave> leaves = pageList.getContent();
//
//        //4、设置总页数
//    	pageUtil.setTotalPages(pageList.getTotalPages());
//
//    	//5、返回前台数据
//    	model.addAttribute("pageUtil", pageUtil);
//        model.addAttribute("leaves", leaves);
        return "leaveStudent/index";
    }

    /**
     * 列表数据-请假流程历史
     * @param model
     * @param pageUtil
     * @return
     */
    //@RequestMapping("/toLeaveStudentHistory")
    public String toLeaveStudentHistory(Model model,PageUtil pageUtil,HttpSession httpSession) {

        //1、从Session中获取登录学生信息
        //Student sessionStudent = new Student("10012016001001",null,null,null,null);
//        Student sessionStudent = (Student)httpSession.getAttribute("sessionStudent");
//        String studentId = sessionStudent.getStudentId();
//
//        //2、初始化分页工具
//        pageUtil = PageUtil.init(pageUtil);
//        Pageable pageable = PageRequest.of(pageUtil.getPageIndex()-1, pageUtil.getSize());
//
//        //3、查询分页数据
//        List<String> studentIdList = new ArrayList<>();
//        studentIdList.add(studentId);
//        List<String> stateList = new ArrayList<>();
//        stateList.add("1");//申请同意的请假单
//        stateList.add("2");//申请拒绝的请假单
//        stateList.add("3");//申请超期的请假单
//        Page<ALeave> pageList= leaveService.getEntityListWithCodeName(pageable,studentIdList,stateList);
//        List<ALeave> leaves = pageList.getContent();
//
//        //4、设置总页数
//        pageUtil.setTotalPages(pageList.getTotalPages());
//
//        //5、返回前台数据
//        model.addAttribute("pageUtil", pageUtil);
//        model.addAttribute("leaves", leaves);
        return "leaveStudent/leaveHistory";
    }

    /**
     * 跳转增加页面
     * @param model
     * @return
     */
    @RequestMapping("/leaveStudent/toAdd")
    public String toAdd(Model model,HttpSession httpSession) {

        //1从登录后session中取得当前登录学生的信息，取出其班级编号
        //String gradeId = "30012016001001";
        Student sessionStudent = (Student)httpSession.getAttribute("sessionStudent");
        String gradeId = sessionStudent.getGradeId();

        //2根据班级编号获得FacultyGradeTeacher表中其班级的所有任课教师ids
        GradeTeacher gradeTeacher = new GradeTeacher(null,gradeId,null);
        List<GradeTeacher> gradeTeachers = gradeTeacherService.findAll(gradeTeacher);

        //3根据教师ids查询教师详细信息
        List<String> ids = new ArrayList<String>();
        ids.add("0000");//防止list空sql报错
        //遍历facultyGradeTeachers取出教师对象
        for(GradeTeacher fgt : gradeTeachers){
            String teacherId = fgt.getTeacherId();
            ids.add(teacherId);
        }
        List<Teacher> teachers = teacherService.findAllById(ids);

        model.addAttribute("teachers",teachers);

        return "leaveStudent/add";
    }

    /**
     * 增加提交
     * @param leave
     * @return
     */
    @RequestMapping("/leaveStudent/add")
    public String add(ALeave leave,HttpSession httpSession) {

//        //处理请假时多个任课教师逻辑
//
//        //1从登录后session中取得当前登录学生的信息，取出其学号
//        //Student sessionStudent = new Student("10012016001001",null,null,null,null);
//        Student sessionStudent = (Student)httpSession.getAttribute("sessionStudent");
//        String studentId = sessionStudent.getStudentId();
//
//        //2存储主表
//        leave.setStudentId(studentId);
//        leave.setApplyDate(new Date(System.currentTimeMillis()));
//        ALeave aLeaveReturn = leaveService.save(leave);
//
//        //3主表存储成功，返回请假id
//        Integer leaveId = aLeaveReturn.getId();
//
//        //4获得前台传入的教师ids，存储请假子表
//        List<ALeaveInfo> list = new ArrayList<>();
//        String teacherIds = leave.getTeacherIds();//获得前台传入的教师ids
//        String[] teacherIdArr = teacherIds.split(",");
//        for(String teacherId:teacherIdArr){
//            ALeaveInfo aLeaveInfo = new ALeaveInfo(null,leaveId,teacherId);
//            list.add(aLeaveInfo);
//        }
//        leaveInfoService.saveAll(list);
//
//        //5.向学生所在班级的指导员发送请假邮件
//        //5.1查学生所在班级
//        Grade grade = gradeService.getOne(sessionStudent.getGradeId());
//        Teacher teacher = teacherService.getOne(grade.getInstructor());
//        String instructorEmail = teacher.getEmail();
//
//        //邮件标题
//        String title = Constant.EMAIL_TITLE;
//
//        Map<String,String> params = new HashMap<>();
//        params.put("instructorName",teacher.getName());
//        params.put("studentName",sessionStudent.getName());
//        params.put("reason",leave.getReason());
//        params.put("startDate",PubFun.getString(leave.getStartDate()));
//        params.put("endDate",PubFun.getString(leave.getEndDate()));
//        params.put("applyDate",PubFun.getString(leave.getApplyDate()));
//
//        String content = PubFun.getEmailContent(emailTemplate01,params);
//
//        mailService.sendMail(title,content,instructorEmail);

        return "redirect:/toLeaveStudentApply";
    }

    /**
     * 跳转编辑页面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/leaveStudent/toEdit")
    public String toEdit(Model model,Integer id,HttpSession httpSession) {

        //1从登录后session中取得当前登录学生的信息，取出其班级编号
        //Student sessionStudent = new Student(null,null,null,"30012016001001",null);
        Student sessionStudent = (Student)httpSession.getAttribute("sessionStudent");
        String gradeId = sessionStudent.getGradeId();

        //2根据班级编号获得FacultyGradeTeacher表中其班级的所有任课教师ids
        GradeTeacher gradeTeacher = new GradeTeacher(null,gradeId,null);
        List<GradeTeacher> gradeTeachers = gradeTeacherService.findAll(gradeTeacher);

        //3根据教师ids查询教师详细信息
        List<String> ids = new ArrayList<String>();
        ids.add("0000");//防止list空sql报错
        //遍历facultyGradeTeachers取出教师对象
        for(GradeTeacher fgt : gradeTeachers){
            String teacherId = fgt.getTeacherId();
            ids.add(teacherId);
        }
        List<Teacher> teachers = teacherService.findAllById(ids);

        //4.根据id获得请假信息主表
        ALeave leave = leaveService.getOne(id);

        //5.根据请假申请id获得请假子表，用于获得请假申请涉及的教师ids
        ALeaveInfo aLeaveInfo = new ALeaveInfo(null,id,null);
        List<ALeaveInfo> aLeaveInfos = leaveInfoService.findAll(aLeaveInfo);
        String aLeaveInfoTeachers = "";
        for(ALeaveInfo ali : aLeaveInfos){
            aLeaveInfoTeachers = aLeaveInfoTeachers +"," +ali.getTeacherId();
        }

        //6.重新给请假主表的TeacherIds赋值，用于页面上下拉复选框赋值
        leave.setTeacherIds(aLeaveInfoTeachers);

        model.addAttribute("teachers",teachers);
        model.addAttribute("leave", leave);

        return "leaveStudent/edit";
    }

    /**
     * 编辑提交
     * @param leave
     * @return
     */
    @RequestMapping("/leaveStudent/edit")
    public String update(ALeave leave) {
        //处理请假时多个任课教师逻辑

        //1.存储主表,主表初次生成时有申请日期，从数据库中查询该值赋值给leave对象
        Integer leaveId = leave.getId();
        ALeave sourceALeave = leaveService.getOne(leaveId);
        //使用工具，将页面leave对象不为空的值，赋值到数据源sourceALeave中并存储
        UpdateObjectUtil.copyNullProperties(leave,sourceALeave);
        leaveService.edit(sourceALeave);

        //2.请假子表每次不再比对变化，直接处理逻辑：先删除，再新增
        leaveInfoService.deleteByLeaveId(leaveId);

        //3.获得前台传入的教师ids，存储请假子表
        List<ALeaveInfo> list = new ArrayList<>();
        String teacherIds = leave.getTeacherIds();//获得前台传入的教师ids
        String[] teacherIdArr = teacherIds.split(",");
        for(String teacherId:teacherIdArr){
            ALeaveInfo aLeaveInfo = new ALeaveInfo(null,leaveId,teacherId);
            list.add(aLeaveInfo);
        }
        leaveInfoService.saveAll(list);

        return "redirect:/toLeaveStudentApply";
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/leaveStudent/delete")
    public String delete(Integer id) {
        //删除请假主表
        leaveService.delete(id);
        //删除请假子表
        leaveInfoService.deleteByLeaveId(id);
        return "redirect:/toLeaveStudentApply";
    }

    /**
     * 跳转历史请假记录详情页面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/leaveStudent/toLeaveHistoryInfo")
    public String toLeaveHistoryInfo(Model model,Integer id,HttpSession httpSession) {

        //逻辑同申请页面的编辑操作，只是跳转页面不同
        //1从登录后session中取得当前登录学生的信息，取出其班级编号
        //Student sessionStudent = new Student(null,null,null,"30012016001001",null);
        Student sessionStudent = (Student)httpSession.getAttribute("sessionStudent");
        String gradeId = sessionStudent.getGradeId();

        //2根据班级编号获得FacultyGradeTeacher表中其班级的所有任课教师ids
        GradeTeacher gradeTeacher = new GradeTeacher(null,gradeId,null);
        List<GradeTeacher> gradeTeachers = gradeTeacherService.findAll(gradeTeacher);

        //3根据教师ids查询教师详细信息
        List<String> ids = new ArrayList<String>();
        ids.add("0000");//防止list空sql报错
        //遍历facultyGradeTeachers取出教师对象
        for(GradeTeacher fgt : gradeTeachers){
            String teacherId = fgt.getTeacherId();
            ids.add(teacherId);
        }
        List<Teacher> teachers = teacherService.findAllById(ids);

        //4.根据id获得请假信息主表
        ALeave leave = leaveService.getOne(id);

        //5.根据请假申请id获得请假子表，用于获得请假申请涉及的教师ids
        ALeaveInfo aLeaveInfo = new ALeaveInfo(null,id,null);
        List<ALeaveInfo> aLeaveInfos = leaveInfoService.findAll(aLeaveInfo);
        String aLeaveInfoTeachers = "";
        for(ALeaveInfo ali : aLeaveInfos){
            aLeaveInfoTeachers = aLeaveInfoTeachers +"," +ali.getTeacherId();
        }

        //6.重新给请假主表的TeacherIds赋值，用于页面上下拉复选框赋值
        leave.setTeacherIds(aLeaveInfoTeachers);

        //7.将请假审批结果状态码替换为状态值
        List<Dictionary> dicts = dictionaryService.findByCodeTypeAndCode("leaveState",leave.getState());
        Dictionary dict = dicts.get(0);
        dict = dict == null?new Dictionary():dict;
        String stateName = dict.getCodeName();
        leave.setState(stateName);

        model.addAttribute("teachers",teachers);
        model.addAttribute("leave", leave);

        return "leaveStudent/leaveHistoryInfo";
    }

    /**
     * 问卷调查页面跳转
     * @return
     */
    @RequestMapping("/toQuesInfo")
    public String toQuesInfo(){
        return "leaveStudent/quesInfo";
    }
}
